package com.actor;

import java.util.concurrent.ScheduledFuture;

/**
 * @author Dmitry
 */
public class FutureActorRef implements ActorRef {
    private final Actor actor;
    private final int tag;
    private ScheduledFuture timeoutFuture;

    public FutureActorRef(Actor actor, int tag) {
        this.actor = actor;
        this.tag = tag;
    }

    public ScheduledFuture getTimeoutFuture() {
        return timeoutFuture;
    }

    public void setTimeoutFuture(ScheduledFuture timeoutFuture) {
        this.timeoutFuture = timeoutFuture;
    }

    public Actor getActor() {
        return actor;
    }

    public int getTag() {
        return tag;
    }

    private void removeTimeoutFuture() {
        if (timeoutFuture != null) {
            if (!(timeoutFuture.isDone() || timeoutFuture.isCancelled())) {
                timeoutFuture.cancel(false);
            }
        }
    }

    @Override
    public void tell(Object object, ActorRef sender) {
        removeTimeoutFuture();
        MessageWrapperFutureResponse mw = new MessageWrapperFutureResponse(object, sender, tag, null);
        actor.tell(mw);
    }

    @Override
    public void tell(MessageWrapper messageWrapper) {
        removeTimeoutFuture();
        actor.tell(messageWrapper);
    }

    @Override
    public void onError(Throwable throwable, Object value, ActorRef sender) {
        removeTimeoutFuture();
        MessageWrapperFutureResponse mw = new MessageWrapperFutureResponse(value, sender, tag, throwable);
        actor.tell(mw);
    }

}
